/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package sun.sundy.functiontest.utils.zxing.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;

import java.util.Timer;
import java.util.TimerTask;

import sun.sundy.functiontest.R;
import sun.sundy.functiontest.utils.zxing.ScanListener;
import sun.sundy.functiontest.utils.zxing.ScanManager;
import sun.sundy.functiontest.utils.zxing.decoding.Utils;
import sun.sundy.functiontest.utils.zxing.utils.Constant;


/**
 * 二维码扫描使用
 */
public class CaptureActivity extends AppCompatActivity implements ScanListener, View.OnClickListener {

    /**
     * 工作模式 (0-单扫，1-连续扫码)
     */
    private String mMode = "";

    //定时器
    private Timer timer;

    /**
     * 扫码之后返回的数据
     */
    public static final String FIELD_SCAN_RESULT = "scan_result";

    //重启扫码页面
    private static final int INIT_SCAN = 1;

    final int PHOTOREQUESTCODE = 1111;

    SurfaceView scanPreview = null;
    View scanContainer;
    View scanCropView;
    ImageView scanLine;
    ScanManager scanManager;
    TextView iv_light;
    TextView qrcode_g_gallery;
    TextView qrcode_ic_back;

    Button rescan;
    ImageView scan_image;
    ImageView authorize_return;
    private int scanMode;//扫描模型（条形，二维码，全部）

    TextView title;

    TextView scan_hint;
    TextView tv_scan_result;


    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_scan_code);
        timer = new Timer();
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        scanMode = getIntent().getIntExtra(Constant.REQUEST_SCAN_MODE, Constant.REQUEST_SCAN_MODE_ALL_MODE);
        initView();
    }

    private void initView() {
        rescan = findViewById(R.id.service_register_rescan);
        scan_image = findViewById(R.id.scan_image);
        authorize_return = findViewById(R.id.authorize_return);
        title = findViewById(R.id.common_title_TV_center);
        scan_hint = findViewById(R.id.scan_hint);
        tv_scan_result = findViewById(R.id.tv_scan_result);
        scanPreview = findViewById(R.id.capture_preview);
        scanContainer = findViewById(R.id.capture_container);
        scanCropView = findViewById(R.id.capture_crop_view);
        scanLine = findViewById(R.id.capture_scan_line);
        qrcode_g_gallery = findViewById(R.id.qrcode_g_gallery);
        qrcode_g_gallery.setOnClickListener(this);
        qrcode_ic_back = findViewById(R.id.qrcode_ic_back);
        qrcode_ic_back.setOnClickListener(this);
        iv_light = findViewById(R.id.iv_light);
        iv_light.setOnClickListener(this);
        rescan.setOnClickListener(this);
        authorize_return.setOnClickListener(this);
        //构造出扫描管理器
        scanManager = new ScanManager(this, scanPreview, scanContainer, scanCropView, scanLine, scanMode, this);
    }

    @Override
    public void onResume() {
        super.onResume();
        scanManager.onResume();
        rescan.setVisibility(View.INVISIBLE);
        scan_image.setVisibility(View.GONE);
    }

    @Override
    public void onPause() {
        super.onPause();
        scanManager.onPause();
    }

    /**
     * 扫描结果回调
     */
    public void scanResult(Result rawResult, Bundle bundle) {
        //扫描成功后，扫描器不会再连续扫描，如需连续扫描，调用reScan()方法。
        //scanManager.reScan();
//		Toast.makeText(that, "result="+rawResult.getText(), Toast.LENGTH_LONG).show();

        Intent intent = getIntent();
        Bundle mode = intent.getExtras();
        //获取工作模式
        if (null !=mode && mode.getString("mode") != null) {
            mMode = mode.getString("mode");
        }

//        if (!scanManager.isScanning()) { //如果当前不是在扫描状态
//            //设置再次扫描按钮出现
//            rescan.setVisibility(View.VISIBLE);
//            scan_image.setVisibility(View.VISIBLE);
//            Bitmap barcode = null;
//            byte[] compressedBitmap = bundle.getByteArray(DecodeThread.BARCODE_BITMAP);
//            if (compressedBitmap != null) {
//                barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null);
//                barcode = barcode.copy(Bitmap.Config.ARGB_8888, true);
//            }
//            scan_image.setImageBitmap(barcode);
//        }
//        rescan.setVisibility(View.VISIBLE);
//        scan_image.setVisibility(View.VISIBLE);
//        tv_scan_result.setVisibility(View.VISIBLE);
//        tv_scan_result.setText("结果：" + rawResult.getText());

        //扫码返回，把条码带回前一个页面
        if (mMode.equals("0")) {
            //扫码报错
            if (rawResult.getText().equals("")) {
                Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
            } else {
                // System.out.println("Result:"+resultString);
                Intent resultIntent = new Intent();
                Bundle reBundle = new Bundle();
                reBundle.putString(FIELD_SCAN_RESULT, rawResult.getText());
                resultIntent.putExtras(reBundle);
                setResult(RESULT_OK, resultIntent);
            }
            CaptureActivity.this.finish();
        } else {
            //扫码报错
            if (rawResult.getText().equals("")) {
                Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
            }

            // 重新开始扫描
            timer.schedule(new TimerTask() {
                public void run() {
                    handlerRefresh.sendEmptyMessage(INIT_SCAN);
                }
            }, 2000);
        }
    }

    /**
     * 重启扫码功能
     */
    @SuppressLint("HandlerLeak")
    private Handler handlerRefresh = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case INIT_SCAN:
                    //恢复扫描
                    scanManager.reScan();
                    break;
            }
        }
    };

    void startScan() {
        if (rescan.getVisibility() == View.VISIBLE) {
            rescan.setVisibility(View.INVISIBLE);
            scan_image.setVisibility(View.GONE);
            scanManager.reScan();
        }
    }

    @Override
    public void scanError(Exception e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        //相机扫描出错时
        if (e.getMessage() != null && e.getMessage().startsWith("相机")) {
            scanPreview.setVisibility(View.INVISIBLE);
        }
    }

    public void showPictures(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String photo_path;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTOREQUESTCODE:
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(data.getData(), proj, null, null, null);
                    if (cursor.moveToFirst()) {
                        int colum_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        photo_path = cursor.getString(colum_index);
                        if (photo_path == null) {
                            photo_path = Utils.getPath(getApplicationContext(), data.getData());
                        }
                        scanManager.scanningImage(photo_path);
                    }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.qrcode_g_gallery:
                showPictures(PHOTOREQUESTCODE);
                break;
            case R.id.iv_light:
                scanManager.switchLight("");
                break;
            case R.id.qrcode_ic_back:
                finish();
                break;
            case R.id.service_register_rescan://再次开启扫描
                startScan();
                break;
            case R.id.authorize_return:
                finish();
                break;
            default:
                break;
        }
    }

    /*
     * 按back键退出扫码页面
     *
     * @param v
     */
    public void goFinish() {
        // 关闪光灯
        scanManager.switchLight("off");
        finish();
    }

}